<template>
  <el-select
    v-model="currentValue"
    placeholder="请选择分类"
    clearable
    @change="handleChange"
    style="width: 260px"
  >
    <el-option
      v-for="(item, index) in dataList"
      :key="index"
      :label="item.label"
      :value="item.value"
    ></el-option>
    <template #footer>
      <el-button v-if="!isAdding" text bg size="small" type="primary" @click="onAddOption">
        自定义
      </el-button>
      <template v-else>
        <el-input-number
          v-model="optionName"
          :step="2"
          class="option-input"
          placeholder="请输入"
          size="small"
          min="0"
        />
        <el-button type="primary" size="small" @click="onConfirm">确定</el-button>
        <el-button size="small" @click="clear">取消</el-button>
      </template>
    </template>
  </el-select>
</template>
<script setup>
import { ref, watch } from "vue";
const isAdding = ref(false);
const optionName = ref("");
const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: "",
  },
  dataList: {
    type: Array,
    default: [],
  },
});
const emit = defineEmits(["update:modelValue"]);
const currentValue = ref(props.modelValue);

watch(
  () => props.modelValue,
  (newVal) => {
    currentValue.value = newVal;
  },
  { immediate: true }
);
const handleChange = (val) => {
  emit("update:modelValue", val);
};
const onAddOption = () => {
  isAdding.value = true;
};
const onConfirm = () => {
  if (optionName.value) {
    props.dataList.push({
      label: optionName.value,
      value: optionName.value,
    });
    clear();
  }
};
const clear = () => {
  optionName.value = "";
  isAdding.value = false;
};
</script>
